<template>
  <div class="wrap-container">
    <div class="add_form">
      <div class="manage_tit">
        <div class="line"></div>
        <p>填写信息</p>
      </div>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="128px">
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input clearable v-model="form.couponName" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="平台类型" prop="type">
          <el-select
            filterable
            clearable
            v-model="form.type"
            placeholder="请选择平台类型"
            @change="changePlatformType"
          >
            <el-option
              v-for="dict in dict?.type?.platform_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否需发放用户" prop="isSpecify">
          <el-radio-group v-model="form.isSpecify">
            <el-radio :label="'0'">是</el-radio>
            <el-radio :label="'1'">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="运动类型" prop="motionType" v-if="!typeDisabled">
          <el-select
            filterable
            clearable
            v-model="form.motionType"
            placeholder="请选择运动类型"
            @change="changeMotionType"
          >
            <el-option
              v-for="dict in dict?.type?.site_type"
              :key="dict.value"
              :value="Number(dict.value)"
              :label="dict.label"
            />
          </el-select>
        </el-form-item>
        <template v-if="!isDisabled">
          <el-form-item label="场馆" prop="stadiumName">
            <el-select
              v-model="form.stadiumName"
              filterable
              remote
              reserve-keyword
              clearable
              placeholder="请输入场馆名"
              :remote-method="searchStadium"
              :loading="stadiumLoading"
              @change="handleStadiumChange"
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in stadiumOptions"
                :key="item.id"
                :label="item.stadiumName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="场地" prop="siteName">
            <el-select
              v-model="form.siteName"
              filterable
              clearable
              placeholder="请选择场地"
              @change="handleSiteChange"
              :disabled="isDisabled"
            >
              <el-option
                v-for="item in siteOptions"
                :key="item.id"
                :label="item.siteName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="优惠券类型" prop="discountType">
          <el-select
            v-model="form.discountType"
            placeholder="请选择优惠券类型"
            @change="handleChange"
            filterable
            clearable
          >
            <el-option
              v-for="dict in dict?.type?.discount_type"
              :key="dict.value"
              :value="Number(dict.value)"
              :label="dict.label"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="优惠券金额" prop="discountAmount" v-if="!isQMShow">
          <el-input
            maxlength="8"
            v-model="form.discountAmount"
            placeholder="请输入金额"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item v-if="isQMShow">
          <template #label>
            <!--            <i style="margin-right: 4px; color: #ff4949">*</i>-->
            全免券使用时间
          </template>
          <div class="align_center">
            <el-form-item prop="startTime">
              <el-time-select
                placeholder="开始时间"
                v-model="form.startTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:60',
                  end: '24:00',
                }"
                clearable
              >
              </el-time-select>
            </el-form-item>
            <el-form-item prop="endTime">
              <el-time-select
                placeholder="结束时间"
                v-model="form.endTime"
                :picker-options="{
                  start: '00:00',
                  step: '00:60',
                  end: '24:00',
                }"
                clearable
              >
              </el-time-select>
            </el-form-item>
          </div>
        </el-form-item>
        <el-form-item v-if="isMJShow" label="满减券总额度" prop="totalLimit">
          <el-input
            maxlength="8"
            v-model="form.totalLimit"
            placeholder="请输入金额"
            style="width: 100%"
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="领取后有效期（单位：天）" prop="validity">
          <el-input type="number" v-model="form.validity" placeholder="请输入领取后有效期" />
        </el-form-item>
        <el-form-item label="优惠券备注" prop="remark">
          <el-input
            clearable
            type="textarea"
            placeholder="请输入内容"
            v-model="form.remark"
            maxlength="30"
            show-word-limit
            :rows="4"
          />
        </el-form-item>
      </el-form>
      <div class="handle_btn">
        <el-button @click="goBack">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useDict } from '@/utils/dict'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { addCoupon, updateCoupon } from '@/api/coupon/coupon'
import { getSitesByStadiumId, quickSearchStadium } from '@/api/site/site'
import { debounce } from 'lodash'

// 字典数据
const { dict } = useDict({
  dicts: ['site_type', 'discount_type', 'platform_type', 'sys_normal_disable'],
})

// 定义响应式数据
const route = useRoute()
const router = useRouter()
const formRef = ref<FormInstance | null>(null)

const isQMShow = ref(false)
const isMJShow = ref(false)
const isDisabled = ref(false)
const typeDisabled = ref(false)
const stadiumLoading = ref(false)
const stadiumOptions = ref<any[]>([])
const siteOptions = ref<any[]>([])

const form = reactive({
  id: null as number | null,
  couponName: null as string | null,
  type: null as string | null,
  enable: null as number | null,
  stadiumId: null as number | null,
  siteId: null as number | null,
  motionType: null as number | null,
  validity: null as number | null,
  stadiumName: null as number | null,
  siteName: null as number | null,
  startTime: null as string | null,
  endTime: null as string | null,
  discountType: null as number | null,
  totalLimit: 0.0,
  discountAmount: 0.0,
  isSpecify: '1',
  remark: null as string | null,
})

const rules = reactive<FormRules>({
  couponName: [
    {
      required: true,
      message: '请输入优惠券名称',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: '请选择平台类型',
      trigger: 'change',
    },
  ],
  motionType: [
    {
      required: true,
      message: '请选择运动类型',
      trigger: 'change',
    },
  ],
  stadiumName: [
    {
      required: true,
      message: '请选择运动类型',
      trigger: 'change',
    },
  ],
  siteName: [
    {
      required: true,
      message: '请选择场地',
      trigger: 'change',
    },
  ],
  discountType: [
    {
      required: true,
      message: '请选择优惠券类型',
      trigger: 'change',
    },
  ],
  discountAmount: [
    {
      required: true,
      message: '请输入优惠券金额',
      trigger: 'blur',
    },
  ],
  validity: [
    {
      required: true,
      message: '请输入领取后有效期',
      trigger: 'blur',
    },
  ],
  remark: [
    {
      required: true,
      message: '请输入优惠券备注',
      trigger: 'blur',
    },
  ],
  totalLimit: [
    {
      required: true,
      message: '请输入满减券总额度',
      trigger: 'blur',
    },
  ],
  isSpecify: [
    {
      required: true,
      message: '请选择是否需发放用户',
      trigger: 'blur',
    },
  ],
})

onMounted(() => {
  if (route.query.data) {
    Object.assign(form, JSON.parse(route.query.data as string))
    if (form.discountType == 2) {
      isQMShow.value = true
    } else {
      isQMShow.value = false
    }
    isDisabled.value = form.type == 2 || form.type == 3 ? true : false
    typeDisabled.value = form.type == 3 ? true : false
    if (form.stadiumId) {
      handlSearchSiteByStadiumId()
    }
    // nextTick(() => {
    //   formRef.value?.clearValidate()
    // })
    changePlatformType(form.type)
  }
})

const searchStadium = async (query: string) => {
  if (query) {
    stadiumLoading.value = true
    try {
      const res: any = await quickSearchStadium({ keyword: query })
      stadiumOptions.value = res.data || []
    } finally {
      stadiumLoading.value = false
    }
  } else {
    stadiumOptions.value = []
  }
}

// 选中框值改变时触发
const handleStadiumChange = (selectedId: number) => {
  console.log(selectedId)
  form.stadiumId = selectedId
  if (selectedId == null || selectedId == undefined || selectedId == 0) {
    form.siteId = 0
    form.siteName = 0
    siteOptions.value = []
    return
  }
  //  根据场馆ID查找出所有场地信息
  handlSearchSiteByStadiumId()
}

const handleSiteChange = (selectedId: number) => {
  console.log(selectedId)
  form.siteId = selectedId
}

const handlSearchSiteByStadiumId = () => {
  //  根据场馆ID查找出所有场地信息
  getSitesByStadiumId({
    stadiumId: form.stadiumId!,
    type: form.motionType!,
  }).then((res: any) => {
    siteOptions.value = res.data
    console.log(res)
  })
}

// 选择运动类型
const changeMotionType = () => {
  form.siteId = 0
  form.siteName = 0
  if (form.stadiumId) {
    handlSearchSiteByStadiumId()
  }
}

const handleChange = (value: number) => {
  if (value == 2) {
    isQMShow.value = true
    isMJShow.value = false
  } else if (value == 3) {
    isMJShow.value = true
    isQMShow.value = false
  } else {
    isQMShow.value = false
    isMJShow.value = false
  }
  console.log('选中的值：' + value)
}

// 选择平台类型
const changePlatformType = (val: any) => {
  isDisabled.value = val == 2 || val == 3 ? true : false
  typeDisabled.value = val == 3 ? true : false
  if (val == 0) {
    // @ts-ignore
    rules.motionType = []
    // @ts-ignore
    rules.siteName = []
  } else {
    // @ts-ignore
    rules.motionType = [{ required: true, message: '请选择运动类型', trigger: 'change' }]
    // @ts-ignore
    rules.siteName = [{ required: true, message: '请选择场地', trigger: 'change' }]
  }
}

// 提交
const handleSubmit = debounce(
  () => {
    try {
      if (!formRef.value) return
      formRef.value.validate(async (valid) => {
        if (valid) {
          if (form.id) {
            await updateCoupon(form)
          } else {
            await addCoupon(form)
          }
          ElMessage.success('操作成功')
          router.push({ path: '/coupon/index' })
        }
      })
    } catch (e) {
      ElMessage.error((e as Error) || '请求失败，请稍后再试')
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 取消
const goBack = () => {
  router.go(-1)
}
</script>

<style lang="scss" scoped>
.add_form {
  background: #fff;
  padding: 20px 15px;
  height: 100%;
  overflow-y: auto;
  .manage_tit {
    margin-bottom: 24px;
    p {
      margin-left: 13px;
    }
  }
  .user_info {
    flex-wrap: wrap;
  }
  .form_item {
    padding-left: 22px;
  }
  :deep(.el-form) {
    margin-left: 221px;
    .el-form-item {
      margin-right: 46px;
    }
    .el-input,
    .el-select {
      width: 458px;
    }
    .el-textarea {
      width: 458px;
    }

    .el-form-item__label {
      color: #383838;
      font-weight: normal;
      padding-right: 19px;
    }
    .el-input__icon {
      height: 35px;
      line-height: 35px;
    }
  }
  .handle_site {
    display: flex;
    align-items: center;
    margin-bottom: 22px;
    .site_btn {
      width: 36px;
      height: 36px;
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 18px;
        height: 18px;
      }
    }
  }

  .handle_btn {
    display: flex;
    margin-left: 684px;
    margin-top: 45px;
    .el-button {
      width: 70px;
      height: 35px;
      border-radius: 8px;
      color: #383838;
      &.el-button--primary {
        background: #2590fa;
        color: #fff;
      }
      & + .el-button {
        margin-left: 28px;
      }
    }
  }
}
</style>
